package com.sfac.day6_22.service.impl;

import com.sfac.day6_22.dao.UserDao;
import com.sfac.day6_22.entity.Result;
import com.sfac.day6_22.entity.User;
import com.sfac.day6_22.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * User Service Impl
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Override
	@Transactional
	public Result<User> insertUser(User user) {
		if (StringUtils.isBlank(user.getUserName()) ||
				StringUtils.isBlank(user.getPassword())) {
			return new Result<>(500, "用户名或密码为空.");
		}

		User temp = userDao.getUserByUserName(user.getUserName());
		if (temp != null) {
			return new Result<>(500, "用户名重复.");
		}

		user.setCreateDate(LocalDateTime.now());
		userDao.insertUser(user);
		return new Result<>(200, "Insert success.", user);
	}

	@Override
	public Result<User> login(User user) {
		User temp = userDao.getUserByUserNameAndPassword(
				user.getUserName(), user.getPassword());
		if (temp == null) {
			return new Result<>(500, "用户名或密码输入错误。");
		}
		return new Result<>(200, "登录成功.", temp);
	}
}
